package org.eenie.learn.seedquartz.quartz.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.reactivex.functions.Function;
import io.reactivex.observers.DefaultObserver;
import org.eenie.learn.seedquartz.controllers.TicketController;
import org.eenie.learn.seedquartz.model.RemoteSeat;
import org.eenie.learn.seedquartz.model.ShipTicketModel;
import org.eenie.learn.seedquartz.quartz.manage.QuartzManager;
import org.eenie.learn.seedquartz.utils.OrderInfo;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class TicketJob implements Job {

    public static String JOB_ID = "";
    private final static Logger logger = LoggerFactory.getLogger(TicketJob.class);

    @Autowired
    TicketController mTicketController;

    @Autowired
    QuartzManager mQuartzManager;

    @Autowired
    OrderInfo mOrderInfo;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        mTicketController.fetchTicketState()
                .map(new Function<List<ShipTicketModel>, ShipTicketModel>() {
                    @Override
                    public ShipTicketModel apply(List<ShipTicketModel> shipTicketModels) throws Exception {
                        for (ShipTicketModel model : shipTicketModels) {
                            if (model.isActive() && model.getDate().contains("14")) {
                                return model;
                            }
                        }
                        return new ShipTicketModel();
                    }
                })
                .subscribe(new DefaultObserver<ShipTicketModel>() {
                    @Override
                    public void onNext(ShipTicketModel model) {
                        if (model != null && model.isActive()) {
                            mQuartzManager.pauseTask(context.getJobDetail().getKey());
                            mTicketController.sendToWx("有票啦！" + model.getDate() + " " + model.getStartLocation() + " => " + model.getEndLocation() + " 余票：" + model.getCount(), "正在努力抢购中！！！！").subscribe();
                            fetchSeat(model);
                        } else {
                            System.out.println("没票，继续监控");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private void fetchSeat(ShipTicketModel model) {
        mTicketController.fetchTicketInfo(model.getBusid(), model.getTtype())
                .map(new Function<List<RemoteSeat>, RemoteSeat>() {
                    @Override
                    public RemoteSeat apply(List<RemoteSeat> remoteSeats) throws Exception {
                        RemoteSeat seat = null;
                        for (RemoteSeat remoteSeat : remoteSeats) {
                            if (remoteSeat.getTicketType().contains("成人")) {
                                if (seat != null) {
                                    if (Double.parseDouble(seat.getPrice()) > Double.parseDouble(remoteSeat.getPrice())) {
                                        seat = remoteSeat;
                                    }
                                } else {
                                    seat = remoteSeat;
                                }
                            }
                        }
                        return seat;
                    }
                })
                .subscribe(new DefaultObserver<RemoteSeat>() {
                    @Override
                    public void onNext(RemoteSeat seat) {
                        if (seat != null) {
                            mOrderInfo.setSeatModel(seat);
                            submit();

                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private void submit() {
        mTicketController.submit(mOrderInfo.getOrderModels())
                .subscribe(new DefaultObserver<JSONObject>() {
                    @Override
                    public void onNext(JSONObject jsonObject) {
                        if (jsonObject.getBoolean("isSuccess")) {
                            mQuartzManager.pauseTask(SubmitJob.JOB_ID);
                            mQuartzManager.resumeTask(PayNoticeJob.JOB_ID);
                            mTicketController.sendToWx("抢票成功,快去公众号付款吧", JSON.toJSONString(mOrderInfo.getOrderModels())).subscribe();
                        } else {
                            mQuartzManager.resumeTask(SubmitJob.JOB_ID);
                            String msg = jsonObject.getString("Message");
                            mTicketController.sendToWx("下单失败，请速去公众号抢购", msg).subscribe();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        mQuartzManager.resumeTask(SubmitJob.JOB_ID);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


}
